package com.kakavr.split.service;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang3.math.NumberUtils;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;

import com.beust.jcommander.internal.Maps;
import com.github.pagehelper.PageHelper;
import com.kakavr.alipay.service.IAliTransferService;
import com.kakavr.base.exception.ValidateParamException;
import com.kakavr.base.service.BaseService;
import com.kakavr.deposit.service.IDepositLogService;
import com.kakavr.page.Pagination;
import com.kakavr.page.constant.PaginationConstant;
import com.kakavr.result.constant.MsgConstants;
import com.kakavr.shop.service.IShopAdminService;
import com.kakavr.split.dao.ISplitLogDao;
import com.kakavr.util.SessionUtils;
import com.kakavr.wxpay.service.IWXTransferService;

@Service
public class SplitLogService extends BaseService implements ISplitLogService {
	@Resource
	private ISplitLogDao splitLogDao;
	@Resource
	private IShopAdminService shopAdminService;
	@Resource
	private IDepositLogService depositLogService;
	@Resource
	private IWXTransferService wXTransferService;
	@Resource
	private IAliTransferService aliTransferService;
	

	@Override
	public void addSplitLog() {
		info("定时生成分账记录任务启动");
		Map<String, Object> param = Maps.newHashMap();
		param.put("createTime", DateTime.now().toDate());
		List<Map<String, Object>> list = splitLogDao.statisTradeFlowList(param);
		if (null == list || list.isEmpty()) {
			info("无分账产生，定时任务结束");
			return;
		}
		splitLogDao.insertSplitLog(list);
		param.put("flowList", list);
		splitLogDao.updateTradeFlow(param);
		info("定时生成分账记录任务运行结束");
	}

	@Override
	public Pagination<Map<String, Object>> selectSplitLogByPage(
			Map<String, Object> map) {
		PageHelper.startPage(NumberUtils.toInt((String) map
				.get(PaginationConstant.PAGE_NO_NAME)), NumberUtils
				.toInt((String) map.get(PaginationConstant.PAGE_SIZE_NAME)));
		return new Pagination<Map<String,Object>>(splitLogDao.selectSplitList(map));
	}

	@Override
	public void updateSplitLogByExam(Map<String, Object> map) {
		splitLogDao.updateSplitLog(map);
	}

	@Override
	public void updateSplitLog(Map<String, Object> map) {
		Map<String, Object> splitMap = splitLogDao.selectSplitLog(map);//查询分账信息
		if (null == splitMap || splitMap.isEmpty()) {
			return;
		}
		int examStatus = (int) splitMap.get("examStatus");
		if (examStatus != 1) {
			throw new ValidateParamException(MsgConstants.MSG_CODE_5001,
					MsgConstants.MSG_CONTENT_5001);
		}
		int status = (int) splitMap.get("status");
		if (status > 0) {
			throw new ValidateParamException(MsgConstants.MSG_CODE_5002,
					MsgConstants.MSG_CONTENT_5002);
		}
		Object storeId = splitMap.get("storeId");
		map.put("status", 1);
		map.put("wxStastus", 1);
		map.put("aliStatus", 1);
		map.put("adminId", SessionUtils.getUserId());
		map.put("splitTime", DateTime.now().toDate());
		// 总收入
		BigDecimal total = (BigDecimal) splitMap.get("total");
		// 押金
		BigDecimal deposit = (BigDecimal) splitMap.get("deposit");

		BigDecimal zero = new BigDecimal("0");
		BigDecimal balance = zero;
		// 如果总收入小于0，则扣除押金
		if (total.compareTo(zero) < 0) {
			balance = deposit.add(total);
			Map<String, Object> shop = Maps.newHashMap();
			shop.put("id", storeId);
			shop.put("deposit", balance);
			shopAdminService.updateShop(shop);
			depositLogService.addDepositLog(storeId, total,
					balance, 1);
			this.updateSplitLogByExam(map);
			return;
		}
		// 微信收入
		BigDecimal wxAmount = (BigDecimal) splitMap.get("wxAmount");
		// 支付宝收入
		BigDecimal aliAmount = (BigDecimal) splitMap.get("aliAmount");
		// 剩余押金（实际押金-10000）
		/*BigDecimal surpDeposit = new BigDecimal(splitMap.get("surpDeposit")
				.toString());
		// 如果前期已经欠费，则补齐押金
		if (surpDeposit.compareTo(zero) < 0) {
			balance = total.add(surpDeposit);
			Map<String, Object> shop = Maps.newHashMap();
			shop.put("id", splitMap.get("storeId"));
			// 变动金额
			if (balance.compareTo(zero) <= 0) {
				deposit = total.add(deposit);
				map.put("offset", total);
				this.updateSplitLogByExam(map);
				shop.put("deposit", deposit);
				shopAdminService.updateShop(shop);
				depositLogService.addDepositLog(storeId, total,
						deposit, 0);
				return;
			}
			map.put("offset", surpDeposit.abs());
			shop.put("deposit", 10000);
			shopAdminService.updateShop(shop);
			depositLogService.addDepositLog(storeId,
					surpDeposit.abs(), 10000, 0);
		}*/
		int wxStastus = (int) splitMap.get("wxStastus");
		// 微信分账
		if (wxStastus < 1) {
			if(balance.compareTo(zero) > 0){
				wxAmount = balance;
				aliAmount = zero;
			}
			//走微信分账接口
			map.put("wxActAmount", wxAmount);
			if(wxAmount.compareTo(zero) > 0){
				wxStastus = wXTransferService.addSplitPayLog(storeId, splitMap.get("openid"),splitMap.get("splitId"), wxAmount);
			}else{
				wxStastus = 1;
			}
		}
		int aliStatus = (int) splitMap.get("aliStatus");
		// 支付宝分账
		if (aliStatus < 1) {
			map.put("aliActAmount", aliAmount);
			if(aliAmount.compareTo(zero) > 0){
				aliStatus = aliTransferService.addSplitPayLog(storeId, splitMap.get("payeeAccount"),splitMap.get("splitId"), aliAmount);
			}else{
				aliStatus = 1;
			}
		}
		map.put("wxStastus", wxStastus);
		map.put("aliStatus", aliStatus);
		this.updateSplitLogByExam(map);
	}

	@Override
	public Map<String, Object> selectSplitInfo(Map<String, Object> map) {
		return splitLogDao.selectSplitInfo(map);
	}

	@Override
	public Map<String, Object> statisticsSplit(Map<String, Object> map) {
		return splitLogDao.statisticsSplit(map);
	}
}
